import ctypes
import os
import sys

import matplotlib
import matplotlib.pyplot as plt
import openpyxl
from PyQt5.QtCore import QDateTime, QTimer, QDate, Qt
from PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBox, QTableWidgetItem, QHeaderView, QLineEdit
from PyQt5 import QtGui, QtWidgets, QtCore
from PyQt5.QtGui import *
import xlrd
from mailmerge import MailMerge
from docx import Document
from docx.shared import Cm
from docx.enum.table import WD_TABLE_ALIGNMENT
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
import docx

from functools import partial

import bird_testing_system_login
import bird_testing_system_mainwindow
import bird_testing_system_history
import bird_testing_system_inquire

import cv2
import numpy as np
import threading
import win32file
from win32api import Sleep
import time
import xlwt
###全局变量，云台执行驱鸟动作的标志位
bird = False
###云台动作子线程退出标志位
exit_c = True
###任务中途退出标志位，按ESC退出
exit_m = True
###工作人员检测标志位
person_f = False

def Sys_init():
    #云台初始化 #串口传输数据 其中# 0 停止 1 左 2 右 3 上 4 下 5 关激光 6 开激光 7 关云台 8 开云台 9 回中
    win32file.WriteFile(file_handle, data1[8])  # 开云台
    Sleep(8000)
    win32file.WriteFile(file_handle,data1[9])  # 回中
    Sleep(8000)
    win32file.WriteFile(file_handle, data1[6])  # 开激光
    Sleep(1000)
    win32file.WriteFile(file_handle,data1[5])  # 关激光
    Sleep(500)

def Program_exit():
    # 程序退出
    win32file.WriteFile(file_handle, data1[5])  # 关激光
    Sleep(500)
    win32file.WriteFile(file_handle, data1[7])  # 关云台
    Sleep(500)
    # 将串口释放
    win32file.CloseHandle(file_handle)
    Sleep(500)
    #系统退出
    exit(0)

###云台驱鸟动作定义
def yuntai():
    win32file.WriteFile(file_handle, data1[6])  # 开激光
    Sleep(100)
    win32file.WriteFile(file_handle, data1[2])
    Sleep(1500)
    win32file.WriteFile(file_handle, data1[4])
    Sleep(200)
    win32file.WriteFile(file_handle, data1[0])
    Sleep(300)
    win32file.WriteFile(file_handle, data1[1])
    Sleep(4000)
    win32file.WriteFile(file_handle, data1[3])
    Sleep(400)
    win32file.WriteFile(file_handle, data1[0])
    Sleep(100)
    win32file.WriteFile(file_handle, data1[2])
    Sleep(3000)
    win32file.WriteFile(file_handle, data1[9])  # 回中
    Sleep(6000)
    win32file.WriteFile(file_handle, data1[5])  # 关激光

###云台驱鸟动作定义
def yuntai_l():
    win32file.WriteFile(file_handle, data1[6])  # 开激光
    Sleep(100)
    win32file.WriteFile(file_handle, data1[1])
    Sleep(1500)
    win32file.WriteFile(file_handle, data1[3])
    Sleep(200)
    win32file.WriteFile(file_handle, data1[0])
    Sleep(300)
    win32file.WriteFile(file_handle, data1[2])
    Sleep(4000)
    win32file.WriteFile(file_handle, data1[9])  # 回中
    Sleep(6000)
    win32file.WriteFile(file_handle, data1[5])  # 关激光

###驱鸟动作控制子线程
def Contral():
    global bird, exit_c, person_f,exit_m, yun_m
    exit_c = True
    time_now = time.strftime("%H", time.localtime())
    time_n = int (time_now)
    while exit_c and (6 <= time_n <= 18):
        ui_mainwindow.tableWidget.scrollToBottom()
        time_now = time.strftime("%H", time.localtime())
        time_n = int(time_now)
        if exit_m == False:
            break
        if bird == True and person_f == False:
            cout('---------------激光开启---------------')
            if yun_m == 1:
                yuntai_l()
                print('left')
            else:
                yuntai()
                print('right')

            cout('---------------激光关闭---------------')
            Sleep(10000)
            bird = False
            cout('---------------等待下次---------------')
    cout('---------驱鸟动作控制子线程退出----------')

####背景建模线程
def createBackgroundSubtractorKNN():
    dir = time.strftime('%Y%m%d', time.localtime())
    dir_d = 'E:/save/' + dir + '/'
    dir_s = 'E:/save/' + dir + '.xlsx'
    dir_w = dir + '.xlsx'
    line = 0
    if not os.path.exists(dir_d):
        os.mkdir(dir_d)
    dir_pic = 'E:/pic/' + dir + '/'
    if not os.path.exists(dir_pic):
        os.mkdir(dir_pic)
    for root, dirs, files in os.walk('E:/save'):  # path 为根目录

        if dir_w in files:
            book = openpyxl.load_workbook(dir_s)
            sheet1 = book['Sheet1']
            line = int(sheet1.cell(1, 1).value) + 1
            break

        else:
            book = openpyxl.Workbook()
            sheet1 = book.create_sheet('Sheet1')
            line = 2

    ####载入模型
    net = cv2.dnn.readNet("./bp/yolo-fastest-bp_6000.weights", "./bp/yolo-fastest-bp.cfg")
    with open("./bp/bp.names", "r") as f:
        classes = [line.strip() for line in f.readlines()]
    layer_names = net.getLayerNames()
    output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]
    font = cv2.FONT_HERSHEY_PLAIN

    cap = cv2.VideoCapture(0 + cv2.CAP_DSHOW)
    cap.set(3, 1280)
    cap.set(4, 720)
    cap1 = cv2.VideoCapture(1 + cv2.CAP_DSHOW)
    cap1.set(3, 1280)
    cap1.set(4, 720)
    # cap2 = cv2.VideoCapture(2 + cv2.CAP_DSHOW)
    # cap2.set(3, 1280)
    # cap2.set(4, 720)
    kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))
    kernel1 = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
    fgbg = cv2.createBackgroundSubtractorKNN(history=50)
    backimg_m = cv2.imread('back_m.png')
    backimg_m = cv2.cvtColor(backimg_m, cv2.COLOR_BGR2GRAY)
    ret, backimg_m = cv2.threshold(backimg_m, 200, 255, cv2.THRESH_BINARY | cv2.THRESH_TRIANGLE)
    sav = False
    global bird, exit_c, exit_m, person_f, yun_m
    time_now = time.strftime("%H", time.localtime())
    ####time_n 用于判断时间段
    time_n = int(time_now)
    #####用于前十秒不做处理
    star = time.time()
    cout_w = 0
    while  6 <= time_n <= 18:
        time_now = time.strftime("%H", time.localtime())
        time_n = int(time_now)
        if exit_m == False:
            break
        #ret, frame = cap.read()

        ret, frame = cap.read()
        ret1, frame1 = cap1.read()
        # ret2, frame2 = cap2.read()
        h, w, d = frame.shape
        pix = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        pix1 = cv2.cvtColor(frame1, cv2.COLOR_BGR2RGB)
        # pix2 = cv2.cvtColor(frame2, cv2.COLOR_BGR2RGB)
        pix = QImage(pix.data, w, h, w * d, QImage.Format_RGB888)
        pix1 = QImage(pix1.data, w, h, w * d, QImage.Format_RGB888)
        # pix2 = QImage(pix2.data, w, h, w * d, QImage.Format_RGB888)
        pix = QPixmap.fromImage(pix)
        pix1 = QPixmap.fromImage(pix1)
        # pix2 = QPixmap.fromImage(pix2)
        ui_mainwindow.label.setPixmap(pix)
        ui_mainwindow.label.setScaledContents(True)
        ui_mainwindow.label_6.setPixmap(pix1)
        ui_mainwindow.label_6.setScaledContents(True)
        # ui_mainwindow.label_4.setPixmap(pix2)
        ui_mainwindow.label_4.setScaledContents(True)

        # ui_mainwindow.label.repaint()
        # ui_mainwindow.label_6.repaint()
        # ui_mainwindow.label_4.repaint()

        im1 = frame[0:550,0:1280]
        im2 = frame[550:720,0:1280]
        star_time = time.strftime("%S", time.localtime())
        time_m = int(star_time)
        if time_m % 4 == 0:
            # 工作人员检测
            person_f = False
            blob = cv2.dnn.blobFromImage(im2, 0.00392, (416, 416), (0, 0, 0), True, crop=False)
            net.setInput(blob)
            outs = net.forward(output_layers)
            # 在屏幕上显示信息
            class_ids = []
            confidences = []
            boxes = []
            for out in outs:
                for detection in out:
                    scores = detection[5:]
                    class_id = np.argmax(scores)
                    confidence = scores[class_id]
                    #####置信度 confidence
                    if confidence > 0.3:
                        # 目标检测
                        center_x = int(detection[0] * 1280)
                        center_y = int(detection[1] * 170)
                        w = int(detection[2] * 1280)
                        h = int(detection[3] * 170)

                        # 绘制矩形框
                        x = int(center_x - w / 2)
                        y = int(center_y - h / 2)

                        boxes.append([x, y, w, h])
                        confidences.append(float(confidence))
                        class_ids.append(class_id)

            indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.8, 0.3)
            for i in range(len(boxes)):
                if i in indexes:
                    label = str(classes[class_ids[i]])
                    if label == "person":
                        person_f = True
                        cout("-------------有工作人员出入------------")
                        x, y, w, h = boxes[i]
                        confidence = confidences[i]
                        cv2.rectangle(frame, (x, y + 550), (x + w, y + 550 + h), (0, 0, 255), 2)
                        cv2.putText(frame, label + " " + str(round(confidence, 2)), (x, y - 10), font, 2, (0, 0, 255), 2)
                        t = time.strftime('%m-%d-%H-%M-%S', time.localtime())
                        cv2.imwrite('E:/person/' + t + 'person.png', frame)
                        continue
        if person_f == True:
            continue

        fgmask = fgbg.apply(im1)
        fgmask = np.where((backimg_m == 255), 0, fgmask)
        fgmask = cv2.morphologyEx(fgmask, cv2.MORPH_OPEN, kernel)
        fgmask = cv2.dilate(fgmask, kernel=kernel1)
        ret, binary = cv2.threshold(fgmask, 200, 255, cv2.THRESH_BINARY | cv2.THRESH_TRIANGLE)
        binary2 = cv2.imread('back_x.png')
        binary2 = cv2.cvtColor(binary2, cv2.COLOR_BGR2GRAY)
        ret, binary2 = cv2.threshold(binary2, 200, 255, cv2.THRESH_BINARY | cv2.THRESH_TRIANGLE)
        binary = np.vstack((binary,binary2))
        # frame1  = cv2.resize(frame, (640,480))
        # binary1 = cv2.resize(binary, (640, 480))
        # cv2.imshow('org', frame1)
        # cv2.imshow('bg', binary1)
        ###按ESC退出
        q = cv2.waitKey(1) & 0xff
        if q == 27:
            exit_c = False
            exit_m = False
            break
        ###开启后前20秒不处理
        if time.time() - star < 20:
            continue
        k = np.sum(binary==255)
        if k >= 90 and k < 1500 and bird == False:
            sav = True
            t = time.strftime('%m-%d-%H-%M-%S', time.localtime())
            xu = t
            #num_objects, labels = cv2.connectedComponents(binary)
            num_objects, labels, stats, centroids = cv2.connectedComponentsWithStats(binary, connectivity=8)
            if 2 <= num_objects <= 4 and (k/(num_objects - 1)) >= 60 :
                cout('---------------这帧有鸟---------------')
                cv2.imwrite(dir_d + t + '-org.png', frame)
                cv2.imwrite(dir_d + t + '-bird.png', binary)
                sheet1.cell(1, 1).value = str(line-1)
                sheet1.cell(line, 1).value = str(t)
                # sheet1.cell(line, 2).value = str(num_objects)
                # sheet1.cell(line, 3).value = str(stats)
                # sheet1.cell(line, 4).value = str(centroids)
                line += 1
                dir_x = 'E:/save/' + dir + '.xls'
                book.save(dir_x)
                dir_xs = 'E:/save/' + dir + '.xlsx'
                book.save(dir_xs)
                if centroids[1][0] <= 640:
                    yun_m = 1
                else:
                    yun_m = 2
                bird = True

                ###star = time.time()
            else:
                ##cout('---------------杂物过多---------------')
                cv2.imwrite('E:/normal/' + t + '.png', binary)

        elif bird == True:
            if sav == True and cout_w < 2:
                cout_w += 1
                s1 = str(cout_w)
                ##E:/pic/用来存储后两帧
                cv2.imwrite(dir_pic + xu + '-' + s1 + '.png', frame)
            else:
                sav = False
                cout_w = 0
        else:
            pass
    dir_x = 'E:/save/' + dir + '.xls'
    book.save(dir_x)
    dir_xs = 'E:/save/' + dir + '.xlsx'
    book.save(dir_xs)
    cap.release()
    cap1.release()
    # cap2.release()
    cout('-------------检测线程退出-------------')


def login(ui_login):#登录界面，登录按钮，登陆功能
    id = ui_login.lineEdit.text()+'\n'
    password = ui_login.lineEdit_2.text()+'\n'
    with open('./id&password/id.txt','r',encoding='utf-8') as idfile,open('./id&password/password.txt','r',encoding='utf-8') as passwordfile:
        ids=idfile.readlines()
        passwords=passwordfile.readlines()
        if id in ids and password == passwords[ids.index(id)]:
            Mainwindow.show()
            #ui_mainwindow.pushButton_12.setEnabled(False)
            Login.close()
        else:
            ui_login.lineEdit.clear()
            ui_login.lineEdit_2.clear()
            ui_login.label_4.setText('账号或密码错误！')
            ui_login.label_4.setStyleSheet("color:red")
            #print('账号或密码错误')

def sign_up(ui_login):#登录界面，注册按钮，注册功能
    id = ui_login.lineEdit.text()
    password = ui_login.lineEdit_2.text()
    with open('./id&password/id.txt', 'a+', encoding='utf-8') as idfile:
        idfile.seek(0)
        ids = idfile.readlines()
        #print(ids)
        if id+'\n' in ids:
            ui_login.label_4.setText('用户名已存在')
            ui_login.label_4.setStyleSheet("color:red")
            #print('用户名已存在')
            ui_login.lineEdit.clear()
            ui_login.lineEdit_2.clear()
        else:
            with open('./id&password/password.txt', 'a+', encoding='utf-8') as passwordfile:
                passwordfile.seek(0)
                idfile.seek(0)
                idfile.write(id+'\n')
                passwordfile.write(password+'\n')
                print(ids, passwordfile.readlines())
        #print(ids)

def self_checking(ui_mainwindow):#主界面，系统自检按钮，系统自检功能
    ip=ui_mainwindow.lineEdit_9.text()
    com1=ui_mainwindow.lineEdit_10.text()
    com2=ui_mainwindow.lineEdit_11.text()
    memorypath=ui_mainwindow.lineEdit.text()
    #print(ip,com1,com2,memorypath)
    if 1:
        ui_mainwindow.pushButton_12.setEnabled(True)
        messageDialog1(ui_mainwindow)
    else:
        messageDialog(ui_mainwindow)

def messageDialog1(self):
	msg_box = QMessageBox(QMessageBox.Information, 'Success', '设备连接正常!')
	msg_box.exec_()

def messageDialog(self):
	msg_box = QMessageBox(QMessageBox.Warning, 'Warning', '自检错误!')
	msg_box.exec_()

def file_name(file_dir):
    L=[]
    for root,dirs,files in os.walk(file_dir):
        for file in files:
            if os.path.splitext(file)[1]=='.png':
                L.append(os.path.join(root,file))
    #print(L)
    return L

def start_test(ui_mainwindow):#主界面，开始检测按钮，检测功能
    global exit_m
    exit_m = True
    t_s = threading.Thread(target=on)
    t_s.start()
    ui_mainwindow.tableWidget.scrollToBottom()

def on():
    global exit_m
    while exit_m:
        ui_mainwindow.tableWidget.scrollToBottom()
        cout('--------------系统初始化--------------')
        # 云台/激光初始化
        Sys_init()
        cout('---------------任务开始---------------')
        threads = [threading.Thread(target=createBackgroundSubtractorKNN),
                   threading.Thread(target=Contral)]
        for t in threads:
            t.setDaemon(True)
            t.start()
        for t in threads:
            t.join()
        win32file.WriteFile(file_handle, data1[5])  # 关激光
        Sleep(1000)
        win32file.WriteFile(file_handle, data1[7])  # 关云台
        Sleep(1000)
        if exit_m == False:
            cout('---------------任务中断---------------')
            break
        cout('---------------天黑了---------------')
        time_now = time.strftime("%H", time.localtime())
        time_n = int(time_now)
        while (time_n < 7) or (time_n > 18):
            if exit_m == False:
                cout('---------------任务中断---------------')
                break
            time_now = time.strftime("%H", time.localtime())
            time_n = int(time_now)
        if exit_m == True:
            cout('---------------新的一天---------------')
    cout('---------------系统退出---------------')
    ###将串口释放
    # win32file.CloseHandle(file_handle)
    # Sleep(500)
    exit(0)

def cout( str_s):
    row = ui_mainwindow.tableWidget.rowCount()
    ui_mainwindow.tableWidget.insertRow(row)
    newItem = QTableWidgetItem(str_s)
    ui_mainwindow.tableWidget.setItem(0,row, newItem)

    # #显示检测数据
    # workbook = xlrd.open_workbook('./datas.xlsx')
    # sheet1=workbook.sheet_by_index(0)
    # cols=sheet1.col_values(0)
    # for i in range(0, len(cols)):
    #     rowlist=sheet1.row_values(i)
    #     for j in range(len(rowlist)):
    #         row=ui_mainwindow.tableWidget.rowCount()
    #         ui_mainwindow.tableWidget.insertRow(row)
    #         newItem=QTableWidgetItem("wck")
    #         ui_mainwindow.tableWidget.setItem(i,j,newItem)
    # for i in range(len(cols),ui_mainwindow.tableWidget.rowCount())[::-1]:
    #     #if ui_history.tableWidget.item(i,0)==None:
    #     ui_mainwindow.tableWidget.removeRow(i)

def showtime(self):
    datetime = QDateTime.currentDateTime()
    text = datetime.toString('yyyy年MM月dd日 hh:mm:ss dddd')
    self.label_26.setText(text)
    self.label_26.setFont(QFont("宋体", 10, QFont.Bold))

def showtime2(self):
    datetime = QDateTime.currentDateTime()
    text = datetime.toString('yyyy年MM月dd日 hh:mm:ss dddd')
    self.label_8.setText(text)
    self.label_8.setFont(QFont("宋体", 10, QFont.Bold))

def choose_path(ui_mainwindow):
    m=QtWidgets.QFileDialog.getExistingDirectory(None,"选取文件夹","C:/")
    ui_mainwindow.lineEdit.setText(m)

def choose_path2(ui_history):
    m = QtWidgets.QFileDialog.getExistingDirectory(None, "选取文件夹", "C:/")
    ui_history.lineEdit_4.setText(m)

def up(ui_mainwindow):
    cout('---------------云台上移---------------')
    # 云台初始化 #串口传输数据 其中# 0 停止 1 左 2 右 3 上 4 下 5 关激光 6 开激光 7 关云台 8 开云台 9 回中
    win32file.WriteFile(file_handle, data1[3])  # 开云台
    Sleep(100)

def down(ui_mainwindow):
    cout('---------------云台下移---------------')
    win32file.WriteFile(file_handle, data1[4])  # 开云台
    Sleep(100)

def left(ui_mainwindow):
    cout('---------------云台左移---------------')
    win32file.WriteFile(file_handle, data1[1])  # 开云台
    Sleep(100)

def stop(ui_mainwindow):
    cout('---------------停止移动---------------')
    win32file.WriteFile(file_handle, data1[0])  # 开云台
    Sleep(100)

def right(ui_mainwindow):
    cout('---------------云台右移---------------')
    win32file.WriteFile(file_handle, data1[2])  # 开云台
    Sleep(100)

def turnonthelaser(ui_mainwindow):
    cout('---------------开启激光---------------')
    win32file.WriteFile(file_handle, data1[6])  # 开云台
    Sleep(100)

def turnoffthelaser(ui_mainwindow):
    cout('---------------关闭激光---------------')
    win32file.WriteFile(file_handle, data1[5])  # 开云台
    Sleep(100)

def turnontheholder(ui_mainwindow):
    cout('---------------开启云台---------------')
    win32file.WriteFile(file_handle, data1[8])  # 开云台
    Sleep(8000)

def turnofftheholder(ui_mainwindow):
    cout('---------------关闭云台---------------')
    win32file.WriteFile(file_handle, data1[7])  # 开云台
    Sleep(100)

def holderbackcenter(ui_mainwindow):
    cout('---------------云台回中---------------')
    win32file.WriteFile(file_handle, data1[9])  # 开云台
    Sleep(6000)

def show_history_window(ui_mainwindow):#主界面，历史查询按钮，调出历史查询窗口
    History.show()
    ui_history.pushButton_3.setEnabled(False)
    #ui_history.pushButton.setEnabled(False)
    #Mainwindow.close()

def show_inquire_window(ui_mainwindow):#主界面，统计分析按钮，调出统计分析窗口
    Inquire.show()
    ui_inquire.pushButton_4.setEnabled(False)
    Mainwindow.close()

def inquire(ui_history):#历史查询界面，查询按钮，历史查询功能
    begindate=ui_history.dateEdit.date().toString('yyyyMMdd')
    #enddate=ui_history.dateEdit_2.date()
    print(begindate)
    if os.path.exists('E:/save/'+begindate)==False:
        ui_history.label_3.setText('当前日期暂无数据')
        ui_history.tableWidget.clearContents()
        ui_history.label_12.setPixmap(QPixmap(""))
        ui_history.label_13.setPixmap(QPixmap(""))
    else:
        path = 'E:/save/'+ begindate
        file_names = file_name(path)
        for filename in file_names:
            if 'org' in filename:
                pix = QPixmap(filename)
                ui_history.label_12.setPixmap(pix)
                ui_history.label_12.setScaledContents(True)
                ui_history.label_12.repaint()
            elif 'bird' in filename:
                pix = QPixmap(filename)
                ui_history.label_13.setPixmap(pix)
                ui_history.label_13.setScaledContents(True)
                ui_history.label_13.repaint()

        #显示检测数据
        ui_history.tableWidget.clearContents()
        workbook = xlrd.open_workbook('E:/save/'+begindate+'.xls')
        sheet1=workbook.sheet_by_index(1)
        cols=sheet1.col_values(0)
        rowlist=sheet1.row_values(0)
        num = str(int(rowlist[0]))

        print(num)
        ui_history.label_3.setText('当日共检测到鸟' + num + '只')

        for i in range(1, len(cols)):
            rowlist=sheet1.row_values(i)
            for j in range(0,len(rowlist)):
                row=ui_history.tableWidget.rowCount()
                ui_history.tableWidget.insertRow(row)
                newItem=QTableWidgetItem(str(rowlist[j]))
                newItem.setFlags(QtCore.Qt.ItemIsSelectable|QtCore.Qt.ItemIsEnabled)
                ui_history.tableWidget.setItem(i-1,j,newItem)
        for i in range(len(cols)-1,ui_history.tableWidget.rowCount())[::-1]:
            #if ui_history.tableWidget.item(i,0)==None:
            ui_history.tableWidget.removeRow(i)
        for i in range(0,len(cols)-1):
            rowlist=sheet1.row_values(i)
            ui_history.updateBtn=QtWidgets.QPushButton('显示本次驱鸟图像')
            ui_history.updateBtn.setStyleSheet(''' text-align : center;
                                            background-color : NavajoWhite;
                                            height : 30px;
                                            border-style: outset;
                                            font : 13px  ''')
            ui_history.tableWidget.setCellWidget(i, len(rowlist) , ui_history.updateBtn)
            ui_history.updateBtn.clicked.connect(partial(update,ui_history))

def styletest(borders,left,right,top,bottom):
    borders.left=left
    borders.right=right
    borders.top=top
    borders.bottom=bottom
    borders.bottom_colour=0x3A

def update(ui_history):
    begindate = ui_history.dateEdit.date().toString('yyyyMMdd')
    path='E:/save/'+begindate
    row = int(ui_history.tableWidget.currentIndex().row())
    filename=path+'/'+ui_history.tableWidget.item(row,0).text()
    #print(filename)
    pix = QPixmap(filename+'-org.png')
    ui_history.label_12.setPixmap(pix)
    ui_history.label_12.setScaledContents(True)
    ui_history.label_12.repaint()
    pix1 = QPixmap(filename + '-bird.png')
    ui_history.label_13.setPixmap(pix1)
    ui_history.label_13.setScaledContents(True)
    ui_history.label_13.repaint()

    '''print('更新数据')
    row=int(ui_history.tableWidget.currentIndex().row())
    print(row)

    question = '是否确认将第' + ui_history.tableWidget.item(row,0).text() + '行数据\"是否成功\"\n由\"' + ui_history.tableWidget.item(
        row, 5).text() + '\"改为\"'
    if ui_history.tableWidget.item(row, 5).text() == '是':
        question += '否\"?'
    else:
        question += '是\"?'
    msg_box=QMessageBox()
    reply=QMessageBox.question(msg_box,'确认修改', question, QMessageBox.Yes | QMessageBox.Cancel)

    if reply==QMessageBox.Yes:
        print('yes')
        workbook = openpyxl.load_workbook('./historydata.xlsx')
        sheet1 = workbook['Sheet1']
        if ui_history.tableWidget.item(row, 5).text() == '是':
            newItem = QTableWidgetItem('否')
        else:
            newItem = QTableWidgetItem('是')
        newItem.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
        ui_history.tableWidget.setItem(row, 5, newItem)
        ui_history.tableWidget.repaint()
        #for j in range(0, 6):
        data = ui_history.tableWidget.item(row, 5).text()
        print(data)
        sheet1.cell(row + 1, 6).value = data
        workbook.save('./historydata.xlsx')'''

def show_main_window(ui_history):#历史查询界面，开始检测按钮，调出主窗口
    Mainwindow.show()
    #ui_mainwindow.pushButton_12.setEnabled(False)
    History.close()

def show_inquire_window1(ui_history):#历史查询界面，统计分析按钮，调出统计分析界面
    Inquire.show()
    ui_inquire.pushButton_4.setEnabled(False)
    History.close()

def reset(ui_history):
    #print('重设时间')
    ui_history.dateEdit.setDate(QDate.currentDate())
    #ui_history.dateEdit_2.setDate(QDate.currentDate())
'''
def check(ui_history):
    print('验证数据')
'''
def show_main_window1(ui_inquire):
    Mainwindow.show()
    #ui_mainwindow.pushButton_12.setEnabled(False)
    Inquire.close()

def show_history_window2(ui_inquire):
    History.show()
    ui_history.pushButton_3.setEnabled(False)
    ui_history.pushButton.setEnabled(False)
    Inquire.close()

def reset1(ui_inquire):
    ui_inquire.dateTimeEdit.setDateTime(QDateTime.currentDateTime())
    ui_inquire.dateTimeEdit_2.setDateTime(QDateTime.currentDateTime())

def create_chart_and_graph(ui_inquire):
    #调出表格
    workbook = xlrd.open_workbook('./inquiredata.xlsx')
    sheet1 = workbook.sheet_by_index(0)
    cols = sheet1.col_values(0)
    for i in range(0, len(cols)):
        rowlist = sheet1.row_values(i)
        for j in range(len(rowlist)):
            row = ui_inquire.tableWidget.rowCount()
            ui_inquire.tableWidget.insertRow(row)
            newItem = QTableWidgetItem(rowlist[j])
            ui_inquire.tableWidget.setItem(i, j, newItem)
    for i in range(len(cols),ui_inquire.tableWidget.rowCount())[::-1]:
        #if ui_history.tableWidget.item(i,0)==None:
        ui_inquire.tableWidget.removeRow(i)
    #生成显示图表
    matplotlib.rcParams["font.sans-serif"]=["SimHei"]
    matplotlib.rcParams["axes.unicode_minus"]=False
    timelist=[]
    testbirdlist=[]
    drivebirdlist=[]
    for i in range(1,len(cols)):
        time=ui_inquire.tableWidget.item(i,0).text()
        testbird=(int)(ui_inquire.tableWidget.item(i,2).text())
        drivebird=int(ui_inquire.tableWidget.item(i,3).text().split("/")[0])
        timelist.append(time)
        testbirdlist.append(testbird)
        drivebirdlist.append(drivebird)
    #print(timelist,testbirdlist,drivebirdlist)
    fig1=plt.figure(figsize=(4,4))
    wedges,texts,autotexts=plt.pie(testbirdlist,labels=timelist,autopct='%1.2f%%',textprops=dict(color="w"))
    plt.legend(wedges,timelist,fontsize=8,title="编号",loc="center left",bbox_to_anchor=(0.9,0.1,0.4,0.4))
    plt.title('鸟类检测数量占比')
    plt.savefig('./fig1.jpg')
    #plt.show()
    pix1=QPixmap('./fig1.jpg')
    ui_inquire.label_9.setPixmap(pix1)
    ui_inquire.label_9.setScaledContents(True)
    ui_inquire.label_9.repaint()

    fig2=plt.figure(figsize=(5,4))
    plt.bar(timelist,testbirdlist)
    plt.title('鸟类检测数量分布')
    plt.xlabel('编号')
    plt.ylabel('检测鸟类数量')
    plt.savefig('./fig2.jpg')
    pix2=QPixmap('./fig2.jpg')
    ui_inquire.label_12.setPixmap(pix2)
    ui_inquire.label_12.setScaledContents(True)
    ui_inquire.label_12.repaint()

    fig3 = plt.figure(figsize=(4,4))
    wedges,texts,autotexts=plt.pie(drivebirdlist, labels=timelist, autopct='%1.2f%%',textprops=dict(color="w"))
    plt.legend(wedges,timelist,fontsize=8,title="编号",loc="center left",bbox_to_anchor=(0.9,0.1,0.4,0.4))
    plt.title('鸟类驱赶数量占比')
    plt.savefig('./fig3.jpg')
    # plt.show()
    pix3 = QPixmap('./fig3.jpg')
    ui_inquire.label_15.setPixmap(pix3)
    ui_inquire.label_15.setScaledContents(True)
    ui_inquire.label_15.repaint()

    fig4 = plt.figure(figsize=(5,4))
    plt.bar(timelist, drivebirdlist)
    plt.title('鸟类驱赶数量分布')
    plt.xlabel('编号')
    plt.ylabel('驱赶鸟类数量')
    plt.savefig('./fig4.jpg')
    pix4 = QPixmap('./fig4.jpg')
    ui_inquire.label_18.setPixmap(pix4)
    ui_inquire.label_18.setScaledContents(True)
    ui_inquire.label_18.repaint()

    ui_inquire.pushButton_8.setEnabled(True)

def create_word(ui_inquire):
    print('word')
    template="./变电站自主侦测驱鸟报告.docx"
    document=MailMerge(template)
    print(document.get_merge_fields())
    num1=0
    count1=0
    sum1=0
    rows=0
    count2=0
    for i in range(1,ui_inquire.tableWidget.rowCount()):
        if ui_inquire.tableWidget.item(i,2)!=None:
            num1+=int(ui_inquire.tableWidget.item(i,2).text())
            if count2<int(ui_inquire.tableWidget.item(i,2).text()):
                count2=int(ui_inquire.tableWidget.item(i,2).text())
                row=i
        if ui_inquire.tableWidget.item(i,3)!=None:
            count1+=int(ui_inquire.tableWidget.item(i,3).text().split("/")[0])
            sum1+=float(ui_inquire.tableWidget.item(i,3).text().split("/")[1].split("%")[0])
            rows+=1
    percent1=sum1/rows
    step=ui_inquire.comboBox.currentText()
    time1=ui_inquire.tableWidget.item(row,1).text()
    percent2=ui_inquire.tableWidget.item(row,3).text().split("/")[1]
    #pic1=xlrd.open_workbook('./inquiredata.xlsx').sheet_by_index(0)
    time=ui_inquire.label_8.text()
    print(step)
    document.merge(
        time=time,
        time0=ui_inquire.dateTimeEdit.dateTime().toString("yyyy/MM/dd HH:mm")+'-'+ui_inquire.dateTimeEdit_2.dateTime().toString("yyyy/MM/dd HH:mm"),
        num1=str(num1),
        count1=str(count1),
        percent1=str(percent1)+'%',
        step=step,
        time1=time1,
        count2=str(count2),
        percent2=percent2,

    )

    savefilename='./变电站自主侦测驱鸟报告'+str(ui_inquire.label_8.text()).replace(" ","").replace(":","")+'.docx'

    print(savefilename)
    document.write(savefilename)
    doc = Document(savefilename)
    print(ui_inquire.tableWidget.rowCount(),ui_inquire.tableWidget.columnCount())

    paragraph = doc.add_paragraph(u'具体数据分析表')
    paragraph.paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
    doc_table=doc.add_table(rows=ui_inquire.tableWidget.rowCount(),cols=ui_inquire.tableWidget.columnCount())


    doc_table.alignment = WD_TABLE_ALIGNMENT.CENTER
    for i in range(0,ui_inquire.tableWidget.rowCount()):
        for j in range(0,ui_inquire.tableWidget.columnCount()):
            if ui_inquire.tableWidget.item(i,j)!=None:
                doc_table.rows[i].cells[j].text=ui_inquire.tableWidget.item(i,j).text()
                doc_table.cell(i,j).paragraphs[0].paragraph_format.alignment=WD_TABLE_ALIGNMENT.CENTER
                if j==0:
                    doc_table.cell(i,j).width=Cm(1.49)
                elif j==1:
                    doc_table.cell(i,j).width=Cm(7.25)
                elif j==2:
                    doc_table.cell(i,j).width=Cm(2.33)
                else:
                    doc_table.cell(i,j).width=Cm(3.66)

    doc_table.style = 'Table Grid'

    picture=doc.add_picture('./fig1.jpg')
    last_paragraph=doc.paragraphs[-1]
    last_paragraph.alignment=docx.enum.text.WD_PARAGRAPH_ALIGNMENT.CENTER
    paragraph = doc.add_paragraph(u'鸟类检测数量扇形统计图')
    paragraph.paragraph_format.alignment=WD_PARAGRAPH_ALIGNMENT.CENTER

    doc.add_picture('./fig2.jpg')
    last_paragraph=doc.paragraphs[-1]
    last_paragraph.alignment=docx.enum.text.WD_PARAGRAPH_ALIGNMENT.CENTER
    paragraph = doc.add_paragraph(u'鸟类检测数量条形统计图')
    paragraph.paragraph_format.alignment=WD_PARAGRAPH_ALIGNMENT.CENTER

    doc.add_picture('./fig3.jpg')
    last_paragraph=doc.paragraphs[-1]
    last_paragraph.alignment=docx.enum.text.WD_PARAGRAPH_ALIGNMENT.CENTER
    paragraph = doc.add_paragraph(u'驱赶率扇形统计图')
    paragraph.paragraph_format.alignment=WD_PARAGRAPH_ALIGNMENT.CENTER

    doc.add_picture('./fig4.jpg')
    last_paragraph=doc.paragraphs[-1]
    last_paragraph.alignment=docx.enum.text.WD_PARAGRAPH_ALIGNMENT.CENTER
    paragraph = doc.add_paragraph(u'驱赶率条形统计图')
    paragraph.paragraph_format.alignment=WD_PARAGRAPH_ALIGNMENT.CENTER
    doc.save(savefilename)

    os.system('start '+savefilename)
def myquit(self):
    global exit_m
    exit_m = False
    #exit(0)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    Login = QMainWindow()
    Mainwindow = QMainWindow()
    History = QMainWindow()
    Inquire = QMainWindow()

    ui_login = bird_testing_system_login.Ui_MainWindow()
    ui_mainwindow = bird_testing_system_mainwindow.Ui_MainWindow()
    ui_history = bird_testing_system_history.Ui_MainWindow()
    ui_inquire = bird_testing_system_inquire.Ui_MainWindow()

    ui_login.setupUi(Login)
    ui_mainwindow.setupUi(Mainwindow)
    ui_history.setupUi(History)
    ui_inquire.setupUi(Inquire)

    window_pale=QtGui.QPalette()
    window_pale.setBrush(QPalette.Background, QtGui.QBrush(QtGui.QPixmap('./background.jpg')))
    Login.setPalette(window_pale)

    ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID("myappid")
    Login.setWindowIcon(QIcon('./bitbug_favicon.ico'))
    Mainwindow.setWindowIcon(QIcon('./bitbug_favicon.ico'))
    History.setWindowIcon(QIcon('./bitbug_favicon.ico'))
    Inquire.setWindowIcon(QIcon('./bitbug_favicon.ico'))

    #Login.show()
    Mainwindow.show()
    #History.show()
    #Inquire.show()

    ui_login.pushButton.clicked.connect(partial(login, ui_login))#登录界面，登录按钮，登陆功能
    ui_login.pushButton_2.clicked.connect(partial(sign_up, ui_login))#登录界面，注册按钮，注册功能
    ui_login.lineEdit_2.setEchoMode(QLineEdit.Password)

    #ui_mainwindow.pushButton_11.clicked.connect(partial(self_checking, ui_mainwindow))#主界面，系统自检按钮，系统自检功能
    ui_mainwindow.pushButton_12.clicked.connect(partial(start_test, ui_mainwindow))#主界面，开始检测按钮，检测功能
    #ui_mainwindow.toolButton.clicked.connect(partial(choose_path, ui_mainwindow))#主界面，选择路径按钮，选择路径
    timer = QTimer(ui_mainwindow.label_26)
    timer.timeout.connect(partial(showtime,ui_mainwindow))
    timer.start()
    ui_mainwindow.pushButton_13.clicked.connect(partial(show_history_window,ui_mainwindow))#主界面，历史查询按钮，调出历史查询窗口
    ui_mainwindow.pushButton_14.clicked.connect(partial(show_inquire_window,ui_mainwindow))#主界面，统计分析按钮，调出统计分析窗口
    ui_mainwindow.pushButton_15.clicked.connect(partial(myquit,ui_mainwindow))#主界面，退出按钮
    ui_mainwindow.pushButton_17.clicked.connect(partial(up,ui_mainwindow))#主界面，上按钮，控制云台向上
    ui_mainwindow.pushButton_20.clicked.connect(partial(left,ui_mainwindow))#主界面，左按钮，控制云台向左
    ui_mainwindow.pushButton_18.clicked.connect(partial(right,ui_mainwindow))#主界面，右按钮，控制云台向右
    ui_mainwindow.pushButton_16.clicked.connect(partial(stop,ui_mainwindow))#主界面，停止按钮，控制云台向停止
    ui_mainwindow.pushButton_19.clicked.connect(partial(down,ui_mainwindow))#主界面，下按钮，控制云台向下
    ui_mainwindow.pushButton.clicked.connect(partial(turnonthelaser,ui_mainwindow))#主界面，激光开按钮，控制激光打开
    ui_mainwindow.pushButton_2.clicked.connect(partial(turnoffthelaser,ui_mainwindow))#主界面，激光关按钮，控制激光关闭
    ui_mainwindow.pushButton_3.clicked.connect(partial(turnontheholder,ui_mainwindow))#主界面，云台开按钮，控制云台打开
    ui_mainwindow.pushButton_4.clicked.connect(partial(turnofftheholder,ui_mainwindow))#主界面，云台关按钮，控制云台关闭
    ui_mainwindow.pushButton_5.clicked.connect(partial(holderbackcenter,ui_mainwindow))#主界面，云台回中按钮，控制云台回中

    ui_history.pushButton_6.clicked.connect(partial(inquire,ui_history))#历史查询界面，查询按钮，历史查询功能
    #ui_history.toolButton.clicked.connect(partial(choose_path2,ui_history))#历史查询界面，选择路径按钮，选择路径
    #ui_history.toolButton.setEnabled(False)
    #ui_history.lineEdit.setFocusPolicy(QtCore.Qt.NoFocus)
    #ui_history.lineEdit_2.setFocusPolicy(QtCore.Qt.NoFocus)
    #ui_history.lineEdit_3.setFocusPolicy(QtCore.Qt.NoFocus)
    timer = QTimer(ui_history.label_8)
    timer.timeout.connect(partial(showtime2, ui_history))
    timer.start()
    ui_history.pushButton_2.clicked.connect(partial(show_main_window,ui_history))#历史查询界面，开始检测按钮，调出主窗口
    ui_history.pushButton_4.clicked.connect(partial(show_inquire_window1,ui_history))#历史查询界面，统计分析按钮，调出统计分析界面
    ui_history.pushButton_5.clicked.connect(partial(myquit,ui_history))#历史查询界面，退出按钮
    ui_history.pushButton_7.clicked.connect(partial(reset,ui_history))#历史查询界面，重设按钮，重设起止时间
    #ui_history.pushButton_8.clicked.connect(partial(check,ui_history))#历史查询界面，验证按钮，验证数据
    ui_history.dateEdit.setCalendarPopup(True)
    #ui_history.dateEdit_2.setCalendarPopup(True)
    ui_history.tableWidget.horizontalHeader().setSectionResizeMode(0,QHeaderView.ResizeToContents)
    ui_history.tableWidget.horizontalHeader().setSectionResizeMode(1,QHeaderView.ResizeToContents)

    ui_inquire.pushButton_4.setEnabled(False)#查询界面，历史查询按钮，禁止历史查询
    ui_inquire.pushButton.setEnabled(False)#查询界面，系统自检按钮，禁止系统自检
    ui_inquire.pushButton_8.setEnabled(False)
    ui_inquire.toolButton.setEnabled(False)
    ui_inquire.lineEdit.setFocusPolicy(QtCore.Qt.NoFocus)
    ui_inquire.lineEdit_2.setFocusPolicy(QtCore.Qt.NoFocus)
    ui_inquire.lineEdit_3.setFocusPolicy(QtCore.Qt.NoFocus)
    ui_inquire.lineEdit_4.setFocusPolicy(QtCore.Qt.NoFocus)
    timer=QTimer(ui_inquire.label_8)#时间日期显示
    timer.timeout.connect(partial(showtime2,ui_inquire))
    timer.start()
    ui_inquire.pushButton_2.clicked.connect(partial(show_main_window1,ui_inquire))#查询界面，开始检测按钮，调出主窗口
    ui_inquire.pushButton_3.clicked.connect(partial(show_history_window2,ui_inquire))#查询界面，历史查询按钮，调出历史查询界面
    ui_inquire.pushButton_5.clicked.connect(partial(myquit,ui_inquire))#查询界面，退出按钮
    ui_inquire.comboBox.addItem('年')
    ui_inquire.comboBox.addItem('月')
    ui_inquire.comboBox.addItem('周')
    ui_inquire.comboBox.addItem('日')
    ui_inquire.comboBox.addItem('时')
    ui_inquire.pushButton_7.clicked.connect(partial(reset1,ui_inquire))#查询界面，重置按钮，重置时间日期
    ui_inquire.dateTimeEdit.setCalendarPopup(True)
    ui_inquire.dateTimeEdit_2.setCalendarPopup(True)
    ui_inquire.pushButton_8.clicked.connect(partial(create_word,ui_inquire))#查询界面，生成报表按钮，生成报表
    ui_inquire.pushButton_6.clicked.connect(partial(create_chart_and_graph,ui_inquire))#查询界面，生成图表按钮，生成图表
    ui_inquire.tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
    ui_inquire.tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Interactive)
    ui_inquire.tableWidget.horizontalHeader().setSectionResizeMode(0,QHeaderView.ResizeToContents)
    ui_inquire.tableWidget.horizontalHeader().setSectionResizeMode(1,QHeaderView.ResizeToContents)
    ui_inquire.tableWidget.horizontalHeader().setSectionResizeMode(2,QHeaderView.ResizeToContents)
    ui_inquire.tableWidget.horizontalHeader().setSectionResizeMode(3,QHeaderView.ResizeToContents)
    ui_mainwindow.tableWidget.horizontalHeader().setSectionResizeMode(0, QHeaderView.ResizeToContents)

    if not os.path.exists('E:/normal/'):
        os.mkdir('E:/normal/')
    if not os.path.exists('E:/pic/'):
        os.mkdir('E:/pic/')
    # 通信串口确认，去系统硬件管理里查看对应COM口
    file_handle = win32file.CreateFile('COM4',
                                       win32file.GENERIC_READ | win32file.GENERIC_WRITE,
                                       win32file.FILE_SHARE_WRITE, None,
                                       win32file.OPEN_EXISTING, 0, None)
    # 串口传输数据 其中# 0 停止 1 左 2 右 3 上 4 下 5 关激光 6 开激光 7 关云台 8 开云台 9 回中
    data1 = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
    Sleep(1000)

    sys.exit(app.exec_())